package service;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.example.menhoo.toollibrary.common.helper.DateUtil;
import com.example.menhoo.toollibrary.common.utils.HandlerUtil;
import com.lidroid.xutils.util.LogUtils;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import application.AppApplication;
import application.HttpUrlConstant;
import interfaces.IReturnObject;
import receiver.SignalrReceiver;

/**
 * Created by yanglei on 16/12/12.
 */
public class SignalrService extends UIService {

    IBinder binder=new SignalrBinder();
    WebView webView;
    private Handler mHandler = new Handler();
    public static final String _uniqueUrl = "http://www.menhoo.i8jsfunction.com";
    private PhoneObject phoneObject = new PhoneObject();

    private ActivityManager activityManager;
    private String packageName;
    private boolean isStop = false;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    public class SignalrBinder extends Binder {
        public SignalrService getService(){
            return SignalrService.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        activityManager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
        packageName = this.getPackageName();

        webView= new WebView(this);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setUseWideViewPort(true);//设置此属性，可任意比例缩放
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setBuiltInZoomControls(true);//设置支持缩放
        webSettings.setSupportZoom(true);
        webSettings.setDisplayZoomControls(false);//setDisplayZoomControls是在Android 3.0中新增的API.
        webSettings.setAllowFileAccess(true);  //设置可以访问文件
        webSettings.setNeedInitialFocus(true); //当webview调用requestFocus时为webview设置节点
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true);  //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8"); //默认编码
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//设置页面缓存 LOAD_NO_CACHE 不缓存只从网络获取
//        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        //html5 本地存储
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheMaxSize(1024 * 1024 * 8);

        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(true);
        //html页面可以调用的js对象名称
        webView.addJavascriptInterface(phoneObject, "phoneObject");


        //如果页面中链接，如果希望点击链接继续在当前browser中响应，而不是新开Android的系统browser中响应该链接，必须覆盖 webview的WebViewClient对象
        webView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                if (!UrlLoad(view, url)) {
                    view.loadUrl(url);
                }
                return true;
            }
            //网页载入完成的时候
            public void onPageFinished(WebView view, String url) {
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                //super.onReceivedSslError(view, handler, error);
                handler.proceed();

            }
        });

        loadUrl(HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.Conn));

        new Thread() {
            public void run() {
                try {
                    while (!isStop) {
                        Thread.sleep(1000);

                        if (isAppOnForeground()) {
                            //LogUtils.d("前台运行");
                            HandlerUtil.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    IsConn(new IReturnObject<String>() {
                                        @Override
                                        public void returnResult(String result) {
                                            if(result.equalsIgnoreCase("false")){
                                                Intent it = new Intent();// 创建Intent对象
                                                it.setAction(SignalrReceiver.Action);
                                                it.putExtra("action", "stop");
                                                sendBroadcast(it);
                                                if(!isStop){
                                                    StartSignalr();
                                                }

                                            }
                                            else{
                                                Intent it = new Intent();// 创建Intent对象
                                                it.setAction(SignalrReceiver.Action);
                                                it.putExtra("action", "conn");
                                                sendBroadcast(it);
                                            }
                                            LogUtils.d("signalr运行:"+result);
                                        }
                                    });
                                }
                            });

                        } else {
                            LogUtils.d("后台运行");
                            HandlerUtil.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
//                                    StopSignalr();
                                    executeJavascript("stop()");
                                }
                            });

                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        executeJavascript("stop()");
        //webView.destroy();
    }

    public void loadUrl(final String urlPar) {

        Map<String, String> parm = new HashMap();
        parm.put("__session__", AppApplication.getSession());
        parm.put("device", "android");
        parm.put("t", DateUtil.Now().getTime()+"");

        final String url_ = HttpUrlConstant.getWebSiteFullUrl(urlPar, parm);

        webView.loadUrl(url_);

    }

    /**
     * 传入 js脚本 如executeJavascript("alert('hahaha')")   这个是无返回值的js方法
     */
    public void executeJavascript(String JavascriptStr) {
        webView.loadUrl("javascript:" + JavascriptStr + ";");
    }

    /**
     * 传入 js脚本 如executeJavascript("alert('hahaha')")   这个是有返回值的js方法
     */
    public void executeJavascript(String JavascriptStr, IReturnObject<String> onFinction) {
        phoneObject.setOnFinction(onFinction);
        webView.loadUrl("javascript:window.phoneObject.getResultContext(" + JavascriptStr + ");");
    }
    /**
     * 返回true 则截断原始url的跳转,false继续按原始的url跳转
     *
     * @param view
     * @param url
     * @return 返回true 则截断原始url的跳转,false继续按原始的url跳转
     */
    public boolean UrlLoad(WebView view, final String url) {
        if (url.toLowerCase().indexOf(_uniqueUrl.toLowerCase()) >= 0) {
            Map<String, String> urlParameters = HttpUrlConstant.getUrlParameters(url);

            if (urlParameters == null || !urlParameters.containsKey("json")) {
                return false;
            }

            try {
                final String jsonStr = URLDecoder.decode(urlParameters.get("json").toString(), "UTF-8");

                mHandler.post(new Runnable() {

                    @Override
                    public void run() {

                        try {
                            //
                            final JSONObject jsonObj = new JSONObject(jsonStr);
                            String action = jsonObj.getString("action");
                            String data = "";
                            if(!jsonObj.isNull("data")){
                                data = jsonObj.getString("data");
                            }


                            Intent it = new Intent();// 创建Intent对象
                            it.setAction(SignalrReceiver.Action);
                            it.putExtra("action", action);
                            it.putExtra("data", data);
                            sendBroadcast(it);

                        } catch (Exception e) {
                            e.printStackTrace();
                            LogUtils.e(e.getMessage() + "");
                        }

                    }
                });


            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            return true;
        }
        return false;
    }

    class PhoneObject {

        IReturnObject<String> onFinction = null;

        public void setOnFinction(IReturnObject<String> onFinction) {
            this.onFinction = onFinction;
        }

        /**
         * 主要用于android接受js方法的返回值
         *
         * @param result
         */
        @JavascriptInterface
        public void getResultContext(final String result) {
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    if (onFinction != null) {
                        if (result.equalsIgnoreCase("undefined")) {
                            onFinction.returnResult(null);
                        } else {
                            onFinction.returnResult(result);
                        }

                    }
                }
            });
        }

    }


    /**
     * 连接signalr
     */
    public void StartSignalr() {
        executeJavascript("start()");
    }

    /**
     * 断开signalr
     */
    public void StopSignalr() {
        isStop=true;
        executeJavascript("stop()");
    }

    /**
     * signalr是否连接中
     * @param onfunction
     */
    public void IsConn(IReturnObject<String> onfunction) {
        executeJavascript("isConnection()", onfunction);
    }

    /**
     * 得到的连接signalr方式
     * @param onfunction
     */
    public void GetTransport(IReturnObject<String> onfunction) {
        executeJavascript("getTransport()", onfunction);
    }

    /**
     * 程序是否在前台运行
     * @return
     */
    public boolean isAppOnForeground() {
        // Returns a list of application processes that are running on the device
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null) return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }

        return false;
    }
}
